package com.higgins.lawapp.server;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.apache.commons.lang.ArrayUtils;

import com.higgins.lawapp.client.settings.dataItemModel.DataItemInstanceDTO;
import com.higgins.lawapp.client.settings.dataItemModel.DataItemLevelDTO;
import com.higgins.lawapp.client.settings.dataItemModel.DataItemSourceDTO;
import com.higgins.lawapp.server.dataItemModel.DataItem;
import com.higgins.lawapp.server.dataItemModel.DataItemContainer;
import com.higgins.lawapp.server.dataItemModel.DataItemInstance;
import com.higgins.lawapp.server.dataItemModel.DataItemLevel;
import com.higgins.lawapp.server.dataItemModel.DataItemSource;
import com.higgins.lawapp.server.dataModel.DataSource;
import com.higgins.lawapp.server.dataModel.DataSourceLevel;

public class DataCollectionStoreEngine {
	PersistenceManager pm;

	public void openConnection()	{
		pm=PMF.get().getPersistenceManager();
	}

	public void closeConnection()	{
		pm.close();
	}
	
	public List<DataSource> retrieveDataSources()	{
		Query query=pm.newQuery(DataSource.class, "dataSourceExecute == executeParam");
		query.declareParameters("Boolean executeParam");
		Boolean execute = true;
		List<DataSource> results = (List<DataSource>)query.execute(execute);
		return results;
	}
	
	public DataItemSource retrieveCollectedData(DataSource dataSource)	{				// NEED TO ACTUALLY SEARCH FOT THE DATASOURCE NAME, NOT JUST PICK ALL!!!
		Query query=pm.newQuery(DataItemSource.class);
		List<DataItemSource> results = (List<DataItemSource>)query.execute();
		DataItemSource dataItemSource = null;
		if (results.size()>0)	{
			dataItemSource = results.get(0);
		}
		return dataItemSource;
	}

	public List<DataItemContainer> retrieveLevelDataItems(String levelName)	{
		Query query=pm.newQuery(DataItemContainer.class, "dataLevel == dataLevelParam");
		query.declareParameters("String dataLevelParam");
		List<DataItemContainer> results = (List<DataItemContainer>)query.execute(levelName);
		return results;
	}
	
	public void updateDataItemSource(DataItemSource dataItemSource)	throws Exception	{
		Query query=pm.newQuery(DataItemSource.class, "dataSourceName == nameParam");
		query.declareParameters("String nameParam");
		String parameter = dataItemSource.getDataItemSourceName();
		List<DataItemSource> results = (List<DataItemSource>)query.execute(parameter);
		if (results!=null)	{		// For some reason the dataSource is returned without DataSource Levels (there should be 4)
			DataItemSource dataItemSourceFromTheDataStore;
			if (results.size()>0)	
				dataItemSourceFromTheDataStore = results.get(0);
			else 
				dataItemSourceFromTheDataStore = dataItemSource;				
			
			pm.makePersistent(dataItemSourceFromTheDataStore);
		}
	}
	
	public void update(DataItem dataItem)	{
		try	{
			pm.makePersistent(dataItem);
		} catch (Exception e)	{
			String Exception = e.toString();
		}
	}	

	public void StoreDataItems(DataItemContainer dataItemContainer)	{
		Transaction transaction = null;
		try	{
			transaction = pm.currentTransaction();
			transaction.begin();
			pm.makePersistent(dataItemContainer);
			transaction.commit();
		} catch (Exception e)	{
			String Exception = e.toString();
		} finally	{
			if (transaction.isActive())
				transaction.rollback();
		}
	}
	
	public boolean retrieveInstanceDataItems(DataSourceLevel dataSourceLevel, List<DataItem> newDataItemsForNextLevel, DataItem dataItem)	{
		List<DataItemContainer> containerList = retrieveInstanceDataItemContainers(dataSourceLevel, newDataItemsForNextLevel, dataItem);
		if (containerList!=null)
			if (containerList.size() > 0)
				if (containerList.get(0).getDataItems()!=null)	{
					newDataItemsForNextLevel.addAll(containerList.get(0).getDataItems());
					return true;
				}
		return false;
	}
	
	public List<DataItemContainer> retrieveInstanceDataItemContainers(DataSourceLevel dataSourceLevel, List<DataItem> newDataItemsForNextLevel, DataItem dataItem)	{
		try	{
			DataItemContainer dataItemContainer;
			String url = InternetManager.generateURLText(dataSourceLevel, dataItem);
			openConnection();
			Query query=pm.newQuery(DataItemContainer.class, "url == urlParam");
			query.declareParameters("String urlParam");
			List<DataItemContainer> results = (List<DataItemContainer>)query.execute(url);
			if (results.size() > 0)	{
				dataItemContainer = results.get(0);
				
				
				
				System.out.println("Hold on a minute!");
			}
			return results;			
		} catch (Exception e)	{
			return null;
		} finally	{
			closeConnection();
		}
	}
	
	
	public void storeDataItemSources(List<DataItemSource> dataItemSourceList)	{
		if (dataItemSourceList!=null)	{
			openDataStoreConnectionAndSave(dataItemSourceList);
		}
	}
	
	private void openDataStoreConnectionAndSave(List<DataItemSource> dataItemSourceList)	{
		String status = "Sucessfully Stored!!!";
		try	{
			if (dataItemSourceList!=null)	{
				Iterator<DataItemSource> iteratorDataItemSource = dataItemSourceList.iterator();
				while(iteratorDataItemSource.hasNext())	{
					DataItemSource dataItemSource = null;
					if (iteratorDataItemSource.hasNext())	{	
						dataItemSource = (DataItemSource)iteratorDataItemSource.next();
						updateDataItemSource(dataItemSource);
					} 
					
					List<DataItemLevel> dataItemLevelList = dataItemSource.getDataItemLevels();
					if (dataItemLevelList!=null)		{
						Iterator<DataItemLevel> iteratorLevel = dataItemLevelList.iterator();
						while(iteratorLevel.hasNext())	{
							DataItemLevel dataItemLevel=null;
							
							if (iteratorLevel.hasNext())	{
								dataItemLevel=iteratorLevel.next();
								pm.makePersistent(dataItemLevel);
							}	
							
							List<DataItemInstance> dataItemInstanceList = dataItemLevel.getDataItemInstances();
							if (dataItemInstanceList!=null)	{
								Iterator<DataItemInstance> instanceIterator = dataItemInstanceList.iterator();
								while(instanceIterator.hasNext())	{
									DataItemInstance dataItemInstance = null;
									
									if (instanceIterator.hasNext())	{
										dataItemInstance = instanceIterator.next();
										pm.makePersistent(dataItemInstance);
									} 
								}
							}
						}
					}
				}
			}
		} 
		catch (Exception e)	{
			status = "Unsuccessfully Stored!! " + e.toString();
		}
		finally {
		}
	}
	

}
